package com.cangxuan.app.ui.user;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.*;

import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.utils.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: 杨刚、田凯
 * Activity: 身份认证
 */
public class MyIdentityActivity extends BaseActivity {
    Uri imageUri;
    EditText editName;
    EditText editNumber;
    Button btnAuthentication;
    Button take_photo;
    ImageView imageView;
    Bitmap bitmap;
    Handler handler = new Handler();

    String path;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_identity);
        editName = findViewById(R.id.editName);
        editNumber = findViewById(R.id.editNumber);
        btnAuthentication = findViewById(R.id.btnAuthentication);

        take_photo = findViewById(R.id.take_photo);
        imageView = findViewById(R.id.picture);
        Permission();
        setTitle("身份认证");

        take_photo.setOnClickListener(v -> openCarema());

        btnAuthentication.setOnClickListener(view -> {

            User user = UserUtils.getUser(context);
            String realName = String.valueOf(editName.getText());
            String idCard = String.valueOf(editNumber.getText());

            if (editName.getText().toString().equals("")) {
                Toast.makeText(this, "请输入真实姓名", Toast.LENGTH_SHORT).show();
                return;
            } else if (editNumber.getText().toString().equals("")) {
                Toast.makeText(this, "请输入身份证号", Toast.LENGTH_SHORT).show();
                return;
            }

            saveBimap(bitmap);
            if (bitmap == null) {
                Toast.makeText(this, "请进行人脸拍摄", Toast.LENGTH_SHORT).show();
                return;
            }

            String imageBase641 = BitmapUtils.convert(bitmap);
            ProgressDialog progressIdentify = ProgressDialog.show(this, "", "请稍等...");

            Log.i("姓名", "输入的姓名是:" + realName);
            Log.i("身份证号码", "输入的身份证号码是:" + idCard);
            Log.i("人脸认证", "人脸认证图片的Base64编码是:" + imageBase641);
            if (imageBase641.equals("")) {
                Toast.makeText(this, "请输入身份证号", Toast.LENGTH_SHORT).show();
                return;
            }

            Map<String, String> header = new HashMap<>();
            header.put("Authorization", DeviceUtils.getDeviceID());

            Thread thread1 = new Thread(() -> {

                JSONObject jsonBody = new JSONObject();
                jsonBody.put("realName", realName);
                jsonBody.put("idCard", idCard);

                String jsonBody1 = HttpUtils.post("/api/user/proveAndUpdateIdentifyInformation/", header, jsonBody.toJSONString(), imageBase641);
                JSONObject jsonResponse = JSONObject.parseObject(jsonBody1);
                if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                    //实名认证成功
                    handler.post(() -> {
                        Toast.makeText(this, "实名认证成功", Toast.LENGTH_SHORT).show();
                        user.setHasSetRealname(true);
                        UserUtils.setUser(this, user);
                        User user1 = UserUtils.getUser(context);
                        progressIdentify.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("user", user1);
                        setResult(1, intent);
                        finish();
                    });
                } else {
                    handler.post(() -> {
                        Toast.makeText(this, jsonResponse.get("message").toString(), Toast.LENGTH_SHORT).show();
                        progressIdentify.dismiss();
                    });
                }
            });

            thread1.start();
        });
    }

    /**
     * 打开相机
     */
    private void openCarema() {
        //启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        path = Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "Camera" + File.separator + RandomUtils.getRandomString(4) + ".jpeg";
        File file = new File(path);
        imageUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                try {
                    // 获取拍照后的图像文件并转换为Bitmap对象
                    bitmap = BitmapUtils.getResizedBitmap(context, path, 800, 800, false);
                    // 根据ImageView的尺寸调整Bitmap对象的大小
                    int imageViewWidth = imageView.getWidth();
                    int imageViewHeight = imageView.getHeight();
                    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, imageViewWidth, imageViewHeight, true);
                    // 设置调整后的Bitmap对象为ImageView的图像
                    imageView.setImageBitmap(resizedBitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    public void Permission() {
        //安卓7.0调用相机
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        //动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS,//联系人的权限
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }

        }

    }

    public void saveBimap(Bitmap bitmap) {
        String name = "sdcard/DCIM/Camera/temp.jpeg";
        File file = new File(name);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}




